const crypto = require("crypto");
const jwt = require("jsonwebtoken");
const userDao = require("../dao/userDao");
const { parseJwt } = require("../utils/tools");

module.exports = {
  register: async (formData) => {
    const hashPwd = crypto
      .createHmac("sha256", process.env.PASSWORD_SALT)
      .update(formData.password)
      .digest("hex");
    formData.password = hashPwd;
    let data = await userDao.register(formData);
    if (data) {
      data = data.toObject();
      delete data.password;
      return {
        data,
      };
    }
    return {
      message: "用户已注册",
    };
  },
  login: async (loginForm) => {
    const hashPwd = crypto
      .createHmac("sha256", process.env.PASSWORD_SALT)
      .update(loginForm.password)
      .digest("hex");
    loginForm.password = hashPwd;
    let data = await userDao.login(loginForm);
    if (data) {
      data = data.toObject();
      if (loginForm.password === data.password) {
        // 设置token
        delete data.password;
        const token = jwt.sign({ data }, process.env.JWT_SECRECT, {
          expiresIn: `${60 * 60 * 24}s`,
        });
        data.token = token;
        data = { ...data };
        return {
          data,
        };
      } else {
        return {
          message: "用户名密码不对",
        };
      }
    } else {
      return {
        message: "用户未注册",
      };
    }
  },
  getUserInfo: (userId) => {
    const data = userDao.getUserInfo(userId)
    if (data) {
      return data
    }
  },
  loginOut: function () {
    console.log("loginout");
  },
};
